<template>
  <div class="project-detail-container">
    <el-page-header @back="goBack" content="项目详情" />
    
    <!-- 第一部分：项目概览 -->
    <el-card class="section-card overview-section">
      <div class="header-section">
        <div class="title-section">
          <h1 class="project-title">{{ project.projectName }}</h1>
          <el-tag :type="getStatusTagType(project.status)" size="large">
            {{ project.status }}
          </el-tag>
        </div>
        <el-divider />
        <div class="basic-info">
          <div class="info-row">
            <div class="info-item">
              <span class="info-label">投资方：</span>
              <span class="info-value">{{ project.investor }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">产业类别：</span>
              <span class="info-value">{{ project.industryCategory }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">所属园区：</span>
              <span class="info-value">{{ project.parkName }}</span>
            </div>
          </div>
          <div class="project-description">
            <div class="description-item">
              <span class="info-label">项目简介：</span>
              <span class="description-content">{{ project.description || '暂无项目简介' }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 第二部分：操作按钮 -->
    <el-card class="section-card action-section">
      <div class="action-buttons">
        <el-button type="primary" @click="handleEdit">
          <el-icon><Edit /></el-icon>编辑
        </el-button>
        <el-button type="warning" @click="handleAssign">
          <el-icon><User /></el-icon>分配
        </el-button>
        <el-button type="info" @click="handleFollowUp">
          <el-icon><DocumentAdd /></el-icon>写跟进
        </el-button>
        <el-button type="success" @click="handleSignContract">
          <el-icon><Document /></el-icon>签订合同
        </el-button>
        <el-button type="danger" @click="handleDelete">
          <el-icon><Delete /></el-icon>删除
        </el-button>
      </div>
    </el-card>

    <!-- 第三部分：简化后的选项卡 -->
    <el-card class="section-card tab-section">
      <el-tabs v-model="activeTab" type="card">
        <el-tab-pane label="项目信息" name="projectInfo">
          <div class="info-table">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="项目编号">{{ project.projectCode }}</el-descriptions-item>
              <el-descriptions-item label="项目类型">
                  <el-tag :type="project.projectType === 'rental' ? 'success' : 'primary'">
                      {{ project.projectType === 'rental' ? '租赁厂房' : '独立选址' }}
                  </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="计划总投资">{{ project.totalInvestment }}万元</el-descriptions-item>
              <el-descriptions-item label="固定资产总投资">{{ project.fixedAssetsInvestment || '-' }}万元</el-descriptions-item>
              <el-descriptions-item label="用地面积">{{ project.landArea }}亩</el-descriptions-item>
              <el-descriptions-item label="产值">{{ project.outputValue || '-' }}万元/年</el-descriptions-item>
              <el-descriptions-item label="纳税额">{{ project.taxRevenue || '-' }}万元/年</el-descriptions-item>
              <el-descriptions-item label="项目类型">{{ project.projectType }}</el-descriptions-item>
              <el-descriptions-item label="项目来源">{{ project.projectSource }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{ project.contactPhone }}</el-descriptions-item>
              <el-descriptions-item label="跟进人">{{ project.follower }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-tab-pane>
        <el-tab-pane label="投资方信息" name="investorInfo">
          <div class="info-table">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="企业名称">{{ project.investor }}</el-descriptions-item>
              <el-descriptions-item label="联系人">{{ project.contactPerson }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{ project.contactPhone }}</el-descriptions-item>
              <el-descriptions-item label="联系地址">{{ project.address || '-' }}</el-descriptions-item>
              <el-descriptions-item label="企业简介">
                <p>{{ project.investorDescription || '暂无企业简介' }}</p>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-tab-pane>
         <!-- 修改后的项目跟进选项卡 -->
          
<el-tab-pane label="项目跟进记录" name="record">
  <div class="follow-up-list">
    <el-timeline>
      <el-timeline-item
        v-for="record in followRecords"
        :key="record.id"
        :timestamp="formatDate(record.followUpDate)"
        placement="top"
      >
        <el-card>
          <p class="follow-content">{{ record.followUpContent }}</p>
          <div class="follow-meta">
            <span>{{ record.followUpPerson }}</span>
            <span>{{ formatTime(record.createdAt) }}</span>
          </div>
        </el-card>
      </el-timeline-item>

      <el-timeline-item v-if="!followRecords.length">
        <el-card>
          <p class="no-data">暂无跟进记录</p>
        </el-card>
      </el-timeline-item>
    </el-timeline>
  </div>
</el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Edit, User, DocumentAdd, Document, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const route = useRoute()
const router = useRouter()
const activeTab = ref('projectInfo')

// 统一使用一个axios实例，包含正确的baseURL
const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,  // 统一添加/api前缀
  timeout: 5000
})

const formatDate = (isoString) => {
  if (!isoString) return '未知日期'
  try {
    return new Date(isoString).toLocaleDateString('zh-CN')
  } catch (e) {
    console.error('日期格式化错误:', e, isoString)
    return isoString
  }
}

const formatTime = (isoString) => {
  if (!isoString) return ''
  try {
    return new Date(isoString).toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (e) {
    console.error('时间格式化错误:', e, isoString)
    return ''
  }
}

const project = ref({})
const followRecords = ref([])

const loadProject = async () => {
  try {
    // 使用统一的api实例，路径正确
    const { data } = await api.get(`/api/projects/${route.params.id}`)
    project.value = data

    const { data: list } = await api.get(`/api/projects/${route.params.id}/follow-ups`)
    followRecords.value = list
  } catch (error) {
    console.error('加载项目详情失败:', error)
    ElMessage.error('加载项目详情失败')
  }
}

// 修复状态标签映射
const getStatusTagType = (status) => {
  const map = {
    '在谈': 'primary',
    '已签约': 'success', 
    '建设中': 'warning',
    '竣工验收': 'info',
    '审核中': '',
    '主任办公室': 'warning'
  }
  return map[status] || 'info'
}

const goBack = () => {
  router.push({ name: 'negotiating' })
}


const handleEdit = () => {
  if (!project.value.id) {
    ElMessage.error('项目ID不存在')
    return
  }
  
  console.log('跳转到编辑页面，项目ID:', project.value.id)
  router.push({
    name: 'ProjectEdit',
    query: {  // 使用 query 而不是 params
      id: project.value.id
    }
  })
}

const handleAssign = () => {
  router.push({ 
    name: 'ProjectAssign',
    query: {  // 使用 query 而不是 params
      id: project.value.id
    }
  })
}

const handleFollowUp = () => {
  router.push({ 
    name: 'ProjectFollowUp',
    query: {  
      id: project.value.id
    }
  })
}

const handleSignContract = () => {
  router.push({ 
    name: 'SignContract',
    query: {  
      id: project.value.id
    }
  })
}

// 修复删除方法
const handleDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除项目【${project.value.projectName}】吗？此操作不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 使用统一的api实例
    await api.delete(`/api/projects/${project.value.id}`)
    ElMessage.success('项目已删除')
    router.push({ name: 'negotiating' })
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error(`删除失败: ${error.response?.data?.message || error.message}`)
    }
  }
}

onMounted(() => {
  loadProject()
})
</script>

<style scoped>
.project-detail-container {
  padding: 20px;
}

.section-card {
  margin-top:20px;
  margin-bottom: 20px;
  border-radius: 8px;
}

.overview-section {
  .header-section {
    .title-section {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      
      .project-title {
        margin: 0;
        font-size: 24px;
        color: #333;
      }
    }
    
    .basic-info {
      .info-row {
        display: flex;
        flex-wrap: wrap;
        gap: 30px;
        margin-bottom: 20px;
        
        .info-item {
          .info-label {
            font-weight: bold;
            color: #666;
          }
          
          .info-value {
            color: #333;
          }
        }
      }
      
      .project-description {
        h3 {
          margin: 20px 0 10px;
          color: #333;
        }
        
        p {
          color: #666;
          line-height: 1.6;
        }
      }
    }
  }
}

.action-section {
  .action-buttons {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    
    .el-button {
      flex: 1;
      min-width: 120px;
    }
  }
}

.tab-section {
  :deep(.el-tabs__header) {
    margin: 0;
  }
  
  :deep(.el-tabs__item) {
    font-size: 16px;
    height: 50px;
    line-height: 50px;
  }
  
  .info-table {
    padding: 10px;
    
    :deep(.el-descriptions__body) {
      background-color: #fafafa;
    }
  }
}
.project-description {
  margin-top: 20px;
}

.description-item {
  display: flex;
  align-items: flex-start;
}

.info-label {
  font-weight: bold;
  color: #666;
  min-width: 80px; /* 保持与上方标签对齐 */
  margin-right: 10px;
}

.description-content {
  color: #333;
  text-align: left;
  white-space: pre-line; /* 保留换行符 */
  word-break: break-word; /* 长单词换行 */
  width: 100%;
}

/* 在InTalkProjectDetail.vue的style部分添加 */
:deep(.el-message-box__message) {
  line-height: 1.5;
}

.delete-confirm {
  color: var(--el-color-danger);
  font-weight: bold;
}

.follow-up-list {
  padding: 10px 0;
}
.follow-content {
  line-height: 1.6;
  white-space: pre-line;
}
.follow-meta {
  margin-top: 10px;
  font-size: 12px;
  color: #888;
  display: flex;
  justify-content: space-between;
}
.no-data {
  color: #999;
  text-align: center;
  padding: 20px 0;
}
</style>